#include <iostream>
#include <unistd.h>
#include <thread>
#include <mutex>
#include <condition_variable>

#include <queue>
std::mutex mutex;

std::condition_variable cond;

void test1(std::queue<int> &q)
{
	while (true)
	{
		{
			std::unique_lock<std::mutex> ul(mutex);
			q.push(rand() % 10000);
			std::cout << "插入数据:" << q.front() << std::endl;
		} // 注意要提前释放锁，否则当前线程会长时间占用锁
		cond.notify_one();
		sleep(1);
	}
}

void test2(std::queue<int> &q)
{
	while (true)
	{
		std::unique_lock<std::mutex> ul(mutex);
		//获取锁并且等待直到队列不为空
		cond.wait(ul, [&q]()
				  { return !q.empty(); });
		std::cout << "删除数据:" << q.front() << std::endl;
		q.pop();
	}
}

int main()
{
	srand(static_cast<unsigned int>(time(0) ^ rand()));
	std::queue<int> q;
	std::thread t1(test1, std::ref(q));
	std::thread t2(test2, std::ref(q));
	t1.join();
	t2.join();

	return 0;
}